# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from report.models import Product,Exchange,Trade
from django.core.exceptions import  ObjectDoesNotExist
import csv
import os
import codecs

def ReadFile(filePath,encoding):
    with codecs.open(filePath,"r",encoding) as f:
        return f.read()
class Command(BaseCommand):
    help = 'Closes the specified poll for voting'

    # def add_arguments(self, parser):
    #     parser.add_argument('poll_id', nargs='+', type=int)

    def handle(self, *args, **options):
        filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)),'products.csv')

        fh=codecs.open(filepath,"r","gbk")

        reader = csv.reader(fh)

        lines=[]

        for line in reader:
            if line[0]:
                lines.append(line)
        for line in lines[1:]:
            product=Product()
            product.name=line[0]
            product.code=str(line[1]).upper()
            try:
                exchange=Exchange.objects.get(code=str(line[4]).upper())
            except ObjectDoesNotExist:
                exchange=Exchange(code=str(line[4]).upper(),name=line[5])
                exchange.save()
            product.exchange=exchange

            try:
                trade=Trade.objects.get(code=str(line[2]).upper())
            except ObjectDoesNotExist:
                trade=Trade(code=str(line[2]).upper(),name=line[3])
                trade.save()
            product.trade=trade
            product.save()